package com.pf.common.aop;

import com.alibaba.fastjson.JSONObject;
import com.pf.common.anotation.Authentication;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2022/11/25 11:58
 */
@Component
@Aspect
public class AuthenticationAspect {

    @Pointcut("@annotation(com.pf.common.anotation.Authentication)")
    public void pointCut() {

    }

    @Before("pointCut() && @annotation(authentication)")
    public void authentication(JoinPoint joinPoint, Authentication authentication) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String method = request.getMethod();
        String requestURI = request.getRequestURI();
        StringBuffer requestURL = request.getRequestURL();
        String contentType = request.getContentType();
        Signature signature = joinPoint.getSignature();
        String[] parameterNames = ((MethodSignature) signature).getParameterNames();
        Object[] paramArray = joinPoint.getArgs();
        Long projectId = null;
        if (StringUtils.isBlank(contentType)) {
            for (int i = 0; i < parameterNames.length; i++) {
                if ("projectId".equals(parameterNames[i])) {
                    Object value = paramArray[i];
                    if (value != null) {
                        projectId = Long.parseLong(String.valueOf(value));
                        break;
                    }
                }
            }
        } else {
            if (contentType.contains(MediaType.APPLICATION_JSON_VALUE)) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(paramArray[0]));
                Object value = jsonObject.get("projectId");
                if (value != null) {
                    projectId = Long.parseLong(String.valueOf(value));
                }
            }
        }

        System.out.println("projectId=" + projectId);

    }

}
